import Vue from 'vue'
import VueRouter from 'vue-router'
import cookie from 'js-cookie'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/tab',
    component: () => import('@/layout/tabLayout'),
    children: [
      {
        path: '/home',
        component: () => import('@/views/home'),
        meta: {
          title: '首页'
        }
      },
      {
        path: '/classify',
        component: () => import('@/views/classify'),
        meta: {
          title: '分类'
        }
      },
      {
        path: '/car',
        component: () => import('@/views/car'),
        meta: {
          auth: true,
          title: '购物车'
        }
      },
      {
        path: '/my',
        component: () => import('@/views/my'),
        meta: {
          auth: true,
          title: '我的'
        }
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = cookie.get('token')
  if (to.meta.auth) {
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          callbackUrl: to.path
        }
      })
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
